<template>
  <div>
    <div>文件上传</div>
    <input type="file" v-on:change="onChange" />
    <el-button size="mini" class="btn-add" @click="handleAddList()" style="margin-left: 20px">添加</el-button>
  </div>
</template>

<script>
import { read, utils } from 'xlsx';

export default {

  data() {
    return {
      fileList: [],
      tableHead: [],
      tableDate: []
    }
  },
  methods: {
    onChange(e) {
      const file = e.target.files[0];
      const fileReader = new FileReader();

      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = read(data, { type: "binary" });
          const params = [];
          workbook.SheetNames.forEach(item => {
            params.push({
              name: item,
              dataList: utils.sheet_to_json(workbook.Sheets[item])
            });
            this.tableDate.push(utils.sheet_to_json(workbook.Sheets[item]))
          })

          // 将params赋值给fileList
          this.fileList = params;

          if (this.tableDate.length > 0) {
            for (const key in this.tableDate[0][0]) {
              this.tableHead.push(key);
            }
          }
          console.log(this.fileList[0].dataList);
          return params;
        } catch (e) {
          console.log("error:" + e);
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    },
    handleAddList() {
      fetch("http://localhost:8080/employee/insertList", {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(this.fileList[0].dataList)
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.state === 200) {
            this.$message({
              message: '添加成功！',
              type: 'success'
            });
          } else {
            this.$message({
              message: data.message,
              type: 'warning'
            });
          }
        })
        .catch(error => {
          console.error('Error:', error);
          alert('网络请求失败，请稍后再试');
        })
    },

  }
}
</script>

<style scoped></style>